<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="保险方案名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" label="ID" min-width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="保险方案名称" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="保险公司" min-width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.insurance_company ? scope.row.insurance_company.name : '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="保险类型" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="保险金额" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column label="保险费率" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.rate }}%
        </template>
      </el-table-column>
      <el-table-column label="描述" min-width="200" align="center">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="保险方案名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="保险公司" prop="insurance_company_id">
          <el-select v-model="temp.insurance_company_id" class="filter-item" placeholder="请选择保险公司">
            <el-option
              v-for="item in insuranceCompanies"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="保险类型" prop="type">
          <el-input v-model="temp.type" />
        </el-form-item>
        <el-form-item label="保险金额" prop="amount">
          <el-input v-model="temp.amount" type="number" />
        </el-form-item>
        <el-form-item label="保险费率(%)" prop="rate">
          <el-input v-model="temp.rate" type="number" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { http } from '@/api'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'

export default {
  name: 'InsuranceCoverage',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        name: undefined
      },
      insuranceCompanies: [],
      temp: {
        id: undefined,
        name: '',
        insurance_company_id: undefined,
        type: '',
        amount: 0,
        rate: 0,
        description: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑保险方案',
        create: '添加保险方案'
      },
      rules: {
        name: [{ required: true, message: '保险方案名称不能为空', trigger: 'blur' }],
        insurance_company_id: [{ required: true, message: '请选择保险公司', trigger: 'change' }],
        type: [{ required: true, message: '保险类型不能为空', trigger: 'blur' }],
        amount: [{ required: true, message: '保险金额不能为空', trigger: 'blur' }],
        rate: [{ required: true, message: '保险费率不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getInsuranceCompanies()
  },
  methods: {
    getList() {
      this.listLoading = true
      http.insuranceCoverage.page(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.count
        this.listLoading = false
      })
    },
    getInsuranceCompanies() {
      http.insuranceCompany.simpleList().then(response => {
        this.insuranceCompanies = response.data.rows
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        insurance_company_id: undefined,
        type: '',
        amount: 0,
        rate: 0,
        description: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          http.insuranceCoverage.create(null, this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      // 确保保险公司ID正确设置
      if (row.insurance_company) {
        this.temp.insurance_company_id = row.insurance_company.id
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          http.insuranceCoverage.update(tempData.id, tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该保险方案吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        http.insuranceCoverage.delete(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
</style>
